package nl.hva.three2learn.dao;


import java.util.List;

import nl.hva.three2learn.model.LiveSession;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public final class LiveSessionDaoImpl implements LiveSessionDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	public List<LiveSession> findAll() {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from LiveSession");
		
		List<LiveSession> liveSessions = q.list();
		
		session.getTransaction().commit();
		
		return liveSessions;
	}
	
	@Override
	public LiveSession findById(long liveSessionId) {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from LiveSession l where l.id = :id");
		q.setLong("id", liveSessionId);
		
		Object result = q.uniqueResult();
		
		session.getTransaction().commit();
		
		return result != null ? (LiveSession) result : null;
	}

	@Override
	public void save(LiveSession liveSession) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(liveSession);
		session.getTransaction().commit();
	}

	@Override
	public void delete(LiveSession liveSession) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.delete(liveSession);
		session.getTransaction().commit();
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
